#include <iostream>
using namespace std;
using ll = long long;
int main() {
	int T;	cin >> T;
	ll a, b, k, l;

	while (T--) {
		cin >> a >> b >> k >> l;
		if (l == 0 || k == 0)
		{
			cout << a + b << endl;
			continue;
		}
		ll t1 = a / l;
		ll t2 = b / l;
		if (t1 + t2 >= k) {
			// 用完了
			cout << a + b - k * l << endl;
		}
		else {
			a = a % l, b = b % l;
			ll tmp1 = (l - a);
			ll tmp2 = (l - b);
			ll ans = 0;
			// 没用完
			if (t1 + t2 == k - 1) {
				// 剩一个
				// ans = min({ a + b, a + tmp2,b + tmp1 });
                ans = min(a + b,a + tmp2);
                ans = min(ans,b + tmp1);
			}
			else {
				// 剩多个
				// ans = min({ a + b, a + tmp2,b + tmp1,tmp1 + tmp2});
                ans = min(a + b,a + tmp2);
                ans = min(ans,b + tmp1);
                ans = min(ans,tmp1 + tmp2);
			}
			cout << ans << endl;
		}
	}
	return 0;
}